<template>
  <div class="container">
    <a-card class="general-card">
      <template #title>
        <div class="page-header">
          <a-space>
            <a-button shape="circle" @click="goBack">
              <template #icon><icon-arrow-left /></template>
            </a-button>
            <h2>发货操作</h2>
          </a-space>
          <div>
            <a-space>
              <a-tag size="medium" color="blue">{{ outboundDetail?.code || '-' }}</a-tag>
              <a-tag size="medium" :color="getStatusColor(outboundDetail?.status)">
                {{ getStatusText(outboundDetail?.status) }}
              </a-tag>
            </a-space>
          </div>
        </div>
      </template>
      
      <!-- 基础信息区域 -->
      <a-descriptions
        title="基础信息"
        :column="{ xs: 1, sm: 2, md: 3 }"
        :data="basicInfoData"
        :bordered="false"
        size="large"
      />
      
      <!-- 物流发货表单 -->
      <a-card class="general-card mb-4" title="物流发货信息">
        <a-form :model="shippingForm" layout="vertical">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item field="trackingNumber" label="物流单号">
                <a-input
                  v-model="shippingForm.trackingNumber"
                  readonly
                  placeholder="系统自动生成"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="carrier" label="承运商">
                <a-select
                  v-model="shippingForm.carrier"
                  placeholder="请选择物流公司"
                  allow-search
                  :loading="logisticsCompaniesLoading"
                >
                  <a-option 
                    v-for="company in logisticsCompanies" 
                    :key="company.id" 
                    :value="company.name"
                  >
                    {{ company.name }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="shippedTime" label="发货时间">
                <a-date-picker
                  v-model="shippingForm.shippedTime"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="24">
              <a-form-item field="shippingNote" label="发货备注">
                <a-textarea
                  v-model="shippingForm.shippingNote"
                  placeholder="可填写发货相关备注信息"
                  :auto-size="{ minRows: 2, maxRows: 4 }"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      
      <!-- 发货商品列表 -->
      <div class="shipping-area">
        <a-table
          :data="productList"
          :loading="loading.detail"
          :pagination="false"
          :bordered="true"
          row-key="id"
        >
          <template #columns>
            <a-table-column title="商品编码" data-index="productCode" :width="120" />
            <a-table-column title="商品名称" data-index="productName" :width="180" />
            <a-table-column title="规格" data-index="specification" :width="160" />
            <a-table-column title="单位" data-index="unit" :width="80" />
            <a-table-column title="订单数量" data-index="orderQuantity" :width="100" />
            <a-table-column title="已拣货数量" data-index="pickedQuantity" :width="100" />
            
            <a-table-column title="发货数量" :width="150">
              <template #cell="{ record }">
                <span>{{ record.pickedQuantity }}</span>
              </template>
            </a-table-column>
            
            <a-table-column title="差异" :width="100">
              <template #cell="{ record }">
                <span :class="getVarianceClass(record)">{{ record.variance }}</span>
              </template>
            </a-table-column>
            
            <a-table-column title="备注" :width="200">
              <template #cell="{ record }">
                <a-input 
                  v-model="record.remark" 
                  placeholder="备注"
                  :disabled="record.status === 'SHIPPED'"
                />
              </template>
            </a-table-column>
            
            <a-table-column title="状态" :width="100">
              <template #cell="{ record }">
                <a-tag :color="getItemStatusColor(record)">
                  {{ getItemStatusText(record) }}
                </a-tag>
              </template>
            </a-table-column>
          </template>
        </a-table>
        
        <div class="action-bar">
          <a-space>
            <a-button
              type="primary"
              status="success"
              :disabled="!isAllShipped || !outboundDetail"
              @click="completeShipping"
            >
              完成发货
            </a-button>
          </a-space>
        </div>
      </div>
    </a-card>
    
    <!-- 操作反馈组件 -->
    <operation-feedback ref="feedbackRef" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Message } from '@arco-design/web-vue';
import { useOutboundStore } from '@/stores/outbound';
import { IconArrowLeft } from '@arco-design/web-vue/es/icon';
import OperationFeedback from '@/components/feedback/OperationFeedback.vue';
import logisticsApi from '@/api/logistics';
import { formatDate } from '@/utils';

const route = useRoute();
const router = useRouter();
const outboundStore = useOutboundStore();
const feedbackRef = ref(null);

const outboundId = computed(() => route.params.id);
const loading = ref({
  detail: false,
  shipItem: false,
  complete: false
});

// 物流公司相关
const logisticsCompanies = ref([]);
const logisticsCompaniesLoading = ref(false);

// 使用store中的状态
const outboundDetail = computed(() => outboundStore.outboundDetail);
const productList = computed(() => outboundStore.productList);

// 计算属性
const isAllShipped = computed(() => {
  return true; // 始终允许完成发货
});

// 发货表单
const shippingForm = ref({
  trackingNumber: '',
  carrier: '',
  shippedTime: formatDate(new Date()),
  shippingNote: ''
});

// 跟踪活动中的加载消息ID
const activeLoadingMessageIds = ref([]);

// 加载物流公司列表
const fetchLogisticsCompanies = async () => {
  logisticsCompaniesLoading.value = true;
  try {
    const response = await logisticsApi.getLogisticsCompanyList({ status: 1 });
    if (response.code === 0 && response.data && response.data.list) {
      logisticsCompanies.value = response.data.list;
    } else {
      console.error('加载物流公司列表失败:', response.message);
      Message.error('加载物流公司列表失败，请刷新页面重试');
    }
  } catch (error) {
    console.error('加载物流公司列表异常:', error);
    Message.error('加载物流公司列表出错，请稍后重试');
  } finally {
    logisticsCompaniesLoading.value = false;
  }
};

// 生成物流单号
const generateTrackingNumber = () => {
  const timestamp = new Date().getTime().toString().slice(-10);
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  return `WMS${timestamp}${random}`;
};

// 组件挂载后获取数据
onMounted(async () => {
  console.log('组件挂载，准备获取出库单详情');
  
  // 获取路由参数确保ID可用
  if (!route.params.id) {
    Message.error('未找到出库单ID');
    router.push('/outbound/list');
    return;
  }
  
  // 并行加载数据提高效率
  await Promise.all([
    fetchOutboundDetail(),
    fetchLogisticsCompanies()
  ]);
  
  // 初始化默认发货日期为当天
  shippingForm.value.shippedTime = formatDate(new Date());
  
  // 生成默认物流单号
  shippingForm.value.trackingNumber = generateTrackingNumber();
});

// 基础信息数据
const basicInfoData = computed(() => {
  if (!outboundDetail.value) return [];
  
  // 尝试从customer对象直接获取信息（优先级更高）
  const customer = outboundDetail.value.customer || {};
  
  return [
    {
      label: '客户名称',
      value: outboundDetail.value.customerName || customer.name || '未知'
    },
    {
      label: '订单类型',
      value: getOrderTypeText(outboundDetail.value.orderType || outboundDetail.value.type)
    },
    {
      label: '创建时间',
      value: outboundDetail.value.createdTime || outboundDetail.value.created_at || '未知'
    },
    {
      label: '创建人',
      value: outboundDetail.value.createdBy || 
             (outboundDetail.value.user ? (outboundDetail.value.user.nickname || outboundDetail.value.user.username) : '未知')
    },
    {
      label: '客户联系人',
      value: outboundDetail.value.customerContact || customer.contact || '未设置'
    },
    {
      label: '联系电话',
      value: outboundDetail.value.customerPhone || customer.phone || '未设置'
    },
    {
      label: '客户地址',
      value: outboundDetail.value.customerAddress || customer.address || '未设置'
    }
  ];
});

// 获取差异样式类
const getVarianceClass = (record) => {
  if (!record.variance) return 'text-normal';
  return record.variance < 0 ? 'text-danger' : 'text-success';
};

// 返回上一页
const goBack = () => {
  router.push('/outbound/list');
};

// 商品状态颜色
const getItemStatusColor = (status) => {
  if (typeof status === 'string') {
    switch (status) {
      case 'PICKED': return 'orange';   // 已拣货待发货
      case 'SHIPPED': return 'green';   // 已发货
      case 'PARTIAL': return 'blue';    // 部分发货
      case 'EXCEPTION': return 'red';   // 异常
      default: return 'gray';           // 其他状态
    }
  } else {
    // 如果status不是字符串，则可能是传入了record对象
    // 根据picked_quantity和shipped_quantity判断状态
    const record = status;
    if (record.shipped_quantity > 0 || record.shippedQuantity > 0) {
      if ((record.shipped_quantity || record.shippedQuantity) >= (record.quantity || record.orderQuantity)) {
        return 'green'; // 全部发货
      } else {
        return 'blue';  // 部分发货
      }
    } else if (record.picked_quantity > 0 || record.pickedQuantity > 0) {
      return 'orange';  // 已拣货待发货
    } else {
      return 'gray';    // 其他状态
    }
  }
};

// 商品状态文本
const getItemStatusText = (status) => {
  if (typeof status === 'string') {
    switch (status) {
      case 'PICKED': return '待发货';
      case 'SHIPPED': return '已发货';
      case 'PARTIAL': return '部分发货';
      case 'EXCEPTION': return '异常';
      default: return '未知状态';
    }
  } else {
    // 如果status不是字符串，则可能是传入了record对象
    // 根据picked_quantity和shipped_quantity判断状态
    const record = status;
    if (record.shipped_quantity > 0 || record.shippedQuantity > 0) {
      if ((record.shipped_quantity || record.shippedQuantity) >= (record.quantity || record.orderQuantity)) {
        return '已发货';  // 全部发货
      } else {
        return '部分发货'; // 部分发货
      }
    } else if (record.picked_quantity > 0 || record.pickedQuantity > 0) {
      return '待发货';    // 已拣货待发货
    } else {
      return '未拣货';    // 未拣货
    }
  }
};

// 订单状态颜色
const getStatusColor = (status) => {
  // 使用出库store中的状态颜色函数
  return outboundStore.getOutboundStatusColor(status);
};

// 订单状态文本
const getStatusText = (status) => {
  // 使用出库store中的状态文本函数
  return outboundStore.getOutboundStatusText(status);
};

// 订单类型文本
const getOrderTypeText = (type) => {
  // 根据后端 model/inventory.go 中的定义调整
  const typeMap = {
    1: '销售出库',
    2: '领用出库',
    3: '调拨出库',
    4: '退货出库',
    5: '其他出库',
  };
  return typeMap[type] || '未知类型';
};

// 更新差异值
const updateVariance = (record) => {
  if (record.orderQuantity !== undefined && record.pickedQuantity !== undefined) {
    record.variance = record.pickedQuantity - record.orderQuantity;
  } else {
    record.variance = 0;
  }
};

// 辅助函数 - 将日期转换为完整的ISO 8601格式（包含T和时间部分）
const formatDateTimeISO = (dateValue) => {
  if (!dateValue) return new Date().toISOString();
  
  // 如果已经是标准ISO格式，直接返回
  if (typeof dateValue === 'string' && dateValue.includes('T')) {
    return dateValue;
  }
  
  // 如果是Date对象，直接转ISO格式
  if (dateValue instanceof Date) {
    return dateValue.toISOString();
  }
  
  // 转换其他格式日期为ISO标准格式
  try {
    const date = new Date(dateValue);
    if (!isNaN(date.getTime())) {
      return date.toISOString();
    }
  } catch (e) {
    console.error('日期格式转换错误:', e);
  }
  
  // 默认返回当前时间的ISO格式
  return new Date().toISOString();
};

// 辅助函数：显示加载消息并跟踪ID
const showLoadingMessage = (content, duration = 0) => {
  // 确保先清除之前可能存在的同内容消息
  const existingMsgs = activeLoadingMessageIds.value.filter(id => 
    id.includes(content.replace(/\s+/g, '_').substring(0, 20))
  );
  
  existingMsgs.forEach(id => {
    clearLoadingMessage(id);
  });

  // 生成包含内容信息的唯一ID，便于识别
  const contentKey = content.replace(/\s+/g, '_').substring(0, 20);
  const id = `loading_${contentKey}_${Date.now()}`;
  
  Message.loading({
    content: content,
    duration: duration, // 如果设置了duration>0，消息会自动关闭
    id: id
  });
  
  activeLoadingMessageIds.value.push(id);
  
  // 如果设置了duration>0，在duration后自动从跟踪列表中移除
  if (duration > 0) {
    setTimeout(() => {
      clearLoadingMessage(id);
    }, duration);
  }
  
  return id;
};

// 辅助函数：清除特定加载消息
const clearLoadingMessage = (id) => {
  if (id) {
    Message.clear(id);
    activeLoadingMessageIds.value = activeLoadingMessageIds.value.filter(msgId => msgId !== id);
  }
};

// 辅助函数：清除所有加载消息
const clearAllLoadingMessages = () => {
  activeLoadingMessageIds.value.forEach(id => {
    Message.clear(id);
  });
  activeLoadingMessageIds.value = [];
  // 额外确保清除所有消息
  Message.clear();
};

// 组件卸载前清除所有加载消息
onBeforeUnmount(() => {
  clearAllLoadingMessages();
});

// 完成发货操作
const completeShipping = async () => {
  if (!outboundDetail.value) {
    Message.warning('未找到出库单信息');
    return;
  }
  
  if (!validateShippingForm()) {
    return;
  }

  loading.value.complete = true;
  try {
    // 显示加载提示
    const loadingMsgId = showLoadingMessage('正在完成发货...', 2000);
    
    // 构建发货请求数据 - 自动包含所有待发货商品
    const requestData = {
      items: productList.value.map(item => ({
        item_id: item.id,
        shipped_quantity: item.pickedQuantity, // 使用已拣货数量作为发货数量
        note: item.remark || ''
      })),
      tracking_number: shippingForm.value.trackingNumber,
      carrier: shippingForm.value.carrier,
      shipping_cost: 0,
      shipped_time: formatDateTimeISO(shippingForm.value.shippedTime),
      note: shippingForm.value.shippingNote || ''
    };
    
    console.log('发送发货请求数据:', JSON.stringify(requestData));
    
    const result = await outboundStore.completeOutboundShipping(outboundId.value, requestData);

    // 清除加载提示
    clearLoadingMessage(loadingMsgId);

    if (result && result.code === 0) {
      // 确保清除所有消息
      clearAllLoadingMessages();
      
      Message.success('出库单发货完成！');
      // 弹出操作成功提示
      if (feedbackRef.value) {
        feedbackRef.value.showResult({
          status: 'success',
          title: '发货完成',
          description: `出库单 ${outboundDetail.value.code} 已完成发货`,
          primaryAction: {
            text: '返回列表',
            callback: () => {
              // 确保清除所有消息后再跳转
              clearAllLoadingMessages();
              router.push({ path: '/outbound/orders' });
            }
          }
        });
      } else {
        // 确保清除所有消息后再跳转
        clearAllLoadingMessages();
        router.push({ path: '/outbound/orders' });
      }
    } else {
      Message.error(`完成发货失败: ${result?.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('完成发货出错:', error);
    
    // 清除所有消息提示
    clearAllLoadingMessages();
    
    Message.error(`完成发货异常: ${error.message || '未知错误'}`);
  } finally {
    loading.value.complete = false;
  }
};

// 获取出库单详情
const fetchOutboundDetail = async () => {
  if (!outboundId.value) {
    Message.error('未找到出库单ID');
    router.push({ path: '/outbound/list' });
    return;
  }

  loading.value.detail = true;
  try {
    console.log('正在获取出库单详情, ID:', outboundId.value);
    await outboundStore.getOutboundDetail(outboundId.value);
    
    if (!outboundStore.outboundDetail) {
      Message.error('未找到出库单详情');
      router.push({ path: '/outbound/list' });
      return;
    }

    // 更新发货信息表单
    if (outboundStore.outboundDetail) {
      shippingForm.value = {
        trackingNumber: generateTrackingNumber(),
        carrier: outboundStore.outboundDetail.last_carrier || '',
        shippedTime: formatDate(new Date()),
        shippingNote: outboundStore.outboundDetail.last_shipping_note || ''
      };
    }

    // 不再需要处理产品列表的发货数量设置
    console.log('商品列表加载完成');
  } catch (error) {
    console.error('获取出库单详情失败:', error);
    Message.error(`获取出库单详情异常: ${error.message || '未知错误'}`);
  } finally {
    loading.value.detail = false;
  }
};

// 验证发货表单
const validateShippingForm = () => {
  // 验证物流单号
  if (!shippingForm.value.trackingNumber) {
    Message.error('请输入物流单号');
    return false;
  }
  
  // 验证承运商
  if (!shippingForm.value.carrier) {
    Message.error('请选择承运商');
    return false;
  }
  
  return true;
};
</script>

<style scoped>
.container {
  padding: 0 16px 16px;
}

.general-card {
  margin-top: 16px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.step-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 16px;
}

.shipping-area {
  margin-top: 24px;
}

.shipping-form {
  margin-bottom: 24px;
  text-align: left;
}

.action-bar {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.text-success {
  color: #00b42a;
  font-weight: bold;
}

.text-danger {
  color: #f53f3f;
  font-weight: bold;
}

.text-normal {
  color: #86909c;
}
</style>